<?php
namespace App\Helpers;
/**文件上传  综合
 * @param unknown $inof_array=$_FILES
 * @param string $uploads 保存路径 uploads/20201212/ 或 uploads/20201212/1.png 或uploads/20201212/1. 该项为自动后缀
 * @param unknown $allowext 文件类型如gif","jpg","png","wbmp
 * @param number $maxsize 最多上传大小 （字节）
 * @param string $imgFlag 是否检验真图片
 * @return 返回图片地址名称：uploads/jkjsdlfjsdklf.jpg
 */
class Upload{

	/**文件上传  综合
 * @param unknown $inof_array=$_FILES 或者传单张 $_FILES['img']
 * @param string $uploads 保存路径 uploads/20201212/ 或 uploads/20201212/1.png 或uploads/20201212/1. 该项为自动后缀
 * @param string $imgFlag 是否检验真图片
 * @param unknown $allowext 文件类型如gif","jpg","png","wbmp
 * @param number $maxsize 最多上传大小 （字节）

 * @return 返回图片地址名称：uploads/jkjsdlfjsdklf.jpg 或数组
 */
static function uploadFile($_FILES_,$uploads="uploads/",$imgFlag=true,$allowext=array("gif","jpg","jpeg","png","wbmp"),$maxsize=6097152){
    $mes=array();
    $_FILES_checks=self::uploadFile_judge($_FILES_);
    if(count($_FILES_checks)==0){
        return false;
    }
    foreach ($_FILES_checks as $inof_array){
        $img=self::uploadFile_judge_next($inof_array,$uploads,$allowext,$maxsize,$imgFlag);
        if(count(explode('.',$img))>1){
            $mes[]=$img;
        }
    }
    return  count($mes)==1?$mes[0]:$mes;

}


/**多文件上传转  混合类型（多文件或单文件）整理成一个相同的数组 返回
 * @param  $_FILES
 * @return unknown
 */
 private static function uploadFile_judge($_FILES_){
    $i=0;
     $file=array();
    foreach ($_FILES_ as $inof1){
        //判断is_numeric（）是否数字   如果不是为单文件上传 否则 为多文件上传
        //return  is_string($inof1['name']);

            if (!is_array($inof1['name'])){
                //为单文件上传
                if( $inof1['size']>0){
                    $file[$i]=$inof1;
                    $i++;
                }

            }else {
                foreach ($inof1['name'] as $key=>$inof2){
                    if( $inof1['size'][$key]>0){
                        $file[$i]['name'] = $inof2;
                        $file[$i]['type'] = $inof1['type'][$key];
                        $file[$i]['tmp_name'] = $inof1['tmp_name'][$key];
                        $file[$i]['error'] = $inof1['error'][$key];
                        $file[$i]['size'] = $inof1['size'][$key];
                        $i ++;
                    }

                }
                //为多文件上传
        }


    }
    //$file=isset($file)?$file:null;
    return $file;
}



/**单文件上传
 * @param unknown $inof_array 文件名
 * @param string $uploads 路径
 * @param string $name  保存的文件名
 * @param unknown $allowext 文件类型array("gif","jpg","png","wbmp")
 * @param number $maxsize 最大限制
 * @param string $imgFlag 是否验证真图片
 * @return 返回图片名称：jkjsdfkkjdfl.jpg
 */
private static function uploadFile_judge_next($inof_array,$uploads_name="uploads",$allowext=array("gif","jpg","jpeg","png","wbmp"),$maxsize=2097152,$imgFlag=false){
if ($inof_array['error']==UPLOAD_ERR_OK){
        $one1=(substr($uploads_name, 0,1));
        if(substr($uploads_name, 0,2)!='./'){
            $uploads_name='./'.$uploads_name;
        }
         $uploads_name=str_replace('//','/',$uploads_name);
        // 需要判断文件是否通过HTTPPOST方式上传的
        // is_uploaded_file($tmp_name)
        $ext = self::getExt($inof_array['name']);

        // in_array(需判断的, 数组)判断文本是否在数组没有
        if (! in_array($ext, $allowext) && !in_array('*', $allowext)) {
            exit("非法文件上传，请重新选择");
        }
        if ($maxsize < $inof_array['size']) {
            exit("文件太大，请压缩后上传Max(2M)");
        }
        /*if ($imgFlag) {
            // getimagesize($tmp_name)判断是否真图片类型
            $inof = getimagesize($inof_array['tmp_name']);
            if (! $inof) {
                exit("不是真正的图片类型");
            }
        }*/
    $uploads_name_array=explode('.',substr($uploads_name,- 6,6));
        if(count($uploads_name_array)>1){
            if($uploads_name_array[1]==''){
                $destination = $uploads_name. "." . $ext;
            }else{
                $destination = $uploads_name;
            }
        }else{

            if (!is_dir($uploads_name)) {
                mkdir($uploads_name, 0700, true);
            }
            $destination = $uploads_name."/" .self:: getUniName() . "." . $ext;
        }








        if (is_uploaded_file($inof_array['tmp_name'])) {
            if (move_uploaded_file($inof_array['tmp_name'],$destination)) {} else {
                $mes = '文件移动失败';
            }
        }
        $mes=str_replace('./','/',$destination);;
    } else {
        switch ($inof_array['error']) {
            case 1:
                $mes = '超过了配置文件上传文件的大小';
                break;
            case 2:
                $mes = '超过表单设置的上传文件大小';
                break;
            case 3:
                $mes = '文件部分被上传';
                break;
            case 4:
                $mes = '超过表单设置的上传文件大小';
                break;
            case 5:
                $mes = '没有文件被上传';
                break;
            case 6:
                $mes = '没有找到临时目录';
                break;
            case 7:
                $mes = '文件不可写';
                break;
            case 8:
                $mes = '由于PHP的扩展程序中断了文件上传';
                break;
        }

    }
    return str_replace('//','/',$mes);
}
/**生成唯一的字符串 返回（字符串）
 * @return string
 */
static function getUniName(){
    //microtime()；得到但当前时间戳
    //uniqid(,true);生成唯一ID
    return md5(uniqid(microtime(true),true));
}
/**判断扩展名 如 返回（jpg）
 * @param  $filename 需要判断的文件名如sdfsdflk.jpg
 * @return string
 */
static function getExt($filename){
    //strtolower()将所有字母转换成小写
    //end($array)选择最后一个数组
    //explode（分割符，文本）分割字符串 返回数组
    $name=explode(".", $filename);
    return strtolower(end($name));
}





/**图片上传无损裁剪     如 返回（jpg）
 * @param  $filename 需要判断的文件名如sdfsdflk.jpg
 * @return string
 */
static function Croppic($rj){

$imgUrl = session('Croppicimg');

// original sizes
$imgInitW = $_POST['imgInitW'];
$imgInitH = $_POST['imgInitH'];
// resized sizes
$imgW = $_POST['imgW'];
$imgH = $_POST['imgH'];
// offsets
$imgY1 = $_POST['imgY1'];
$imgX1 = $_POST['imgX1'];
// crop box
$cropW = $_POST['cropW'];
$cropH = $_POST['cropH'];
// rotation angle
$angle = $_POST['rotation'];

$jpeg_quality = 100;

$output_filename = "{$rj}croppedImg_".rand();

// uncomment line below to save the cropped image in the same location as the original image.
//$output_filename = dirname($imgUrl). "/croppedImg_".rand();

$what = getimagesize($imgUrl);

switch(strtolower($what['mime']))
{
    case 'image/png':
        $img_r = imagecreatefrompng($imgUrl);
		$source_image = imagecreatefrompng($imgUrl);
		$type = '.png';
        break;
    case 'image/jpeg':
        $img_r = imagecreatefromjpeg($imgUrl);
		$source_image = imagecreatefromjpeg($imgUrl);
		error_log("jpg");
		$type = '.jpeg';
        break;
    case 'image/gif':
        $img_r = imagecreatefromgif($imgUrl);
		$source_image = imagecreatefromgif($imgUrl);
		$type = '.gif';
        break;
    default: die('image type not supported');
}


//Check write Access to Directory

if(!is_writable(dirname($output_filename))){
	$response = Array(
	    "status" => 'error',
	    "message" => 'Can`t write cropped File'
    );
}else{

    // resize the original image to size of editor
    $resizedImage = imagecreatetruecolor($imgW, $imgH);
	imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW, $imgH, $imgInitW, $imgInitH);
    // rotate the rezized image
    $rotated_image = imagerotate($resizedImage, -$angle, 0);
    // find new width & height of rotated image
    $rotated_width = imagesx($rotated_image);
    $rotated_height = imagesy($rotated_image);
    // diff between rotated & original sizes
    $dx = $rotated_width - $imgW;
    $dy = $rotated_height - $imgH;
    // crop rotated image to fit into original rezized rectangle
	$cropped_rotated_image = imagecreatetruecolor($imgW, $imgH);
	imagecolortransparent($cropped_rotated_image, imagecolorallocate($cropped_rotated_image, 0, 0, 0));
	imagecopyresampled($cropped_rotated_image, $rotated_image, 0, 0, $dx / 2, $dy / 2, $imgW, $imgH, $imgW, $imgH);
	// crop image into selected area
	$final_image = imagecreatetruecolor($cropW, $cropH);
	imagecolortransparent($final_image, imagecolorallocate($final_image, 0, 0, 0));
	imagecopyresampled($final_image, $cropped_rotated_image, 0, 0, $imgX1, $imgY1, $cropW, $cropH, $cropW, $cropH);
	// finally output png image
	//imagepng($final_image, $output_filename.$type, $png_quality);
	imagejpeg($final_image, $output_filename.$type, $jpeg_quality);
	$response = Array(
	    "status" => 'success',
	    "url" => '/'.$output_filename.$type
    );
}
return  $response;


}


  static  function makeHeadImg($text='头像',$classstring='0188FB_FFF_100_100',$pathname=null){

        $setting = explode("_",$classstring );
        $img = array();

        switch ($n = count($setting)) {
            case $n > 4 :
            case 3:
                $setting[3] = $setting[2];
            case 4:
                $img['width'] = (int) $setting[2];
                $img['height'] = (int) $setting[3];
            case 2:
                $img['color'] = $setting[1];
                $img['background'] = $setting[0];
                break;
            default:
                list($img['background'],$img['color'],$img['width'],$img['height']) = array('F','0',100,100);
                break;
        }

        $background = explode(",",self::hex2rgb($img['background']));
        $color = explode(",",self::hex2rgb($img['color']));
        $width = empty($img['width']) ? 100 : $img['width'];
        $height = empty($img['height']) ? 100 : $img['height'];
        $string = (string) $text;

        header("Content-Type: image/png");
        $image = @imagecreate($width, $height)
        or die("Cannot Initialize new GD image stream");

        $background_color = imagecolorallocate($image, $background[0], $background[1], $background[2]);
        $text_color = imagecolorallocate($image, $color[0], $color[1], $color[2]);


//截取前二

        $string_zw=substr($string,0,3);
        $substr_length=3;
        if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $string_zw) === 1) {
            $string_zw=substr($string,3,6);
            if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $string_zw) === 1) {
                $substr_length=6;
            }else{
                $substr_length=strlen($string)==3?3:4;
            }

        }else{
            $substr_length=2;
        }
        $string=substr($string,0,$substr_length);

        $font=30;
        if((int)$width!==100){
            $font= $width*30/100;
        }

        $substr_length=$substr_length==4?4.9:$substr_length;
        $multiple=$font*(($substr_length/3)-1);

        $x=($width-$font)/2-$multiple+5;
        $y=($height-$font)/2+30;


// 用 col 颜色将字符串 s 画到 image 所代表的图像的 x，y 座标处（图像的左上角为 0, 0）。
//如果 font 是 1，2，3，4 或 5，则使用内置字体
// 画验证码
        @imagefttext($image, $font , 0, $x, $y, $text_color, './simhei.ttf',$string);
//imagestring($image, 5, $x, $y, $string, $text_color);
        imagepng($image,$pathname);
        imagedestroy($image);


    }
   static function hex2rgb($hex) {
        // Copied
        $hex = str_replace("#", "", $hex);

        switch (strlen($hex)) {
            case 1:
                $hex = $hex.$hex;
            case 2:
                $r = hexdec($hex);
                $g = hexdec($hex);
                $b = hexdec($hex);
                break;

            case 3:
                $r = hexdec(substr($hex,0,1).substr($hex,0,1));
                $g = hexdec(substr($hex,1,1).substr($hex,1,1));
                $b = hexdec(substr($hex,2,1).substr($hex,2,1));
                break;

            default:
                $r = hexdec(substr($hex,0,2));
                $g = hexdec(substr($hex,2,2));
                $b = hexdec(substr($hex,4,2));
                break;
        }

        $rgb = array($r, $g, $b);
        return implode(",", $rgb);
    }


}

